SpringBoot RestTemplate 忽略https证书的方法
忽略Https证书方法
话不多说直接上代码.
添加Http忽略证书代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27public class HttpClientFactory {
private static final int readTimeout = 5000;
private static final int connectTimeout = 5000;
public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
SSLConnectionSocketFactory sslsf = null;
//忽略ssl证书
try {
SSLContext sslContext = org.apache.http.conn.ssl.SSLContexts.custom().useTLS().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} catch (Exception e) {
e.printStackTrace();
}
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout).setStaleConnectionCheckEnabled(true).build();
return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).build();
}
}RestTemplate bean初始代码
1
2
3
4
5
6
7
8
9
10@Bean
@LoadBalanced
RestTemplate restTemplate() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
CloseableHttpClient httpClient = HttpClientFactory.acceptsUntrustedCertsHttpClient();
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
restTemplate.setErrorHandler(new ResponseErrorHandler());
return restTemplate;
}